//
//  BuyNowViewController.m
//  Router
//
//  Created by teki on 15/10/15.
//  Copyright © 2015年 dc. All rights reserved.
//

#import "BindWIFIListViewController.h"
#import "MyViewController.h"
#import "BuyWIFIViewController.h"
#import "BindWiFITableViewCell.h"
#import "UserSingleton.h"
#import "DiscoverHelper.h"
#import "BindDeviceViewController.h"

@interface BindWIFIListViewController ()
@property (nonatomic, strong) UIView *showNoWIFIView;
@property (nonatomic, strong) DiscoverHelper *discoverHelper;
@property (nonatomic, strong) NSDictionary *responseDict;
@end

@implementation BindWIFIListViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.discoverHelper = [[DiscoverHelper alloc] init];
    self.navigationItem.title = @"小叶WIFI管理";
    
    [self addRightBarButtonWithNormalImageName:@"home_my" selectedImageName:@"home_my_pre" target:self action:@selector(rightButtonPressed:)];
    
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(findNewWIFI) name:UIApplicationDidBecomeActiveNotification object:nil];

    
//    LoginResponseModel *model = [UserSingleton shareInstance].userModel;
//    self.contentList = [NSMutableArray arrayWithArray:model.bindDevice];
//    if ([model.bindDevice count] ==0)
//    {
//        
//        [self showNOWIFIDeviceView];
//    }

    [self.tableView registerNib:[UINib nibWithNibName:@"BindWiFITableViewCell" bundle:nil] forCellReuseIdentifier:@"BindWiFITableViewCell"];
    self.tableView.tableFooterView = [UIView new];
    
        // Do any additional setup after loading the view.
}



- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    [self findNewWIFI];
//    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(findNewWIFINotification:) name:TK_FindNewWIFINotification object:nil];

}


//- (void)findNewWIFINotification:(NSNotification *)notify
//{
//    BOOL hasNewWIFI = [[notify object] boolValue];
//    [self addLeftBarButtonWithNormalImageName:@"home_location" selectedImageName:@"home_location_pre" target:self action:@selector(leftButtonPressed:)];
//    self.navigationItem.leftBarButtonItem.customView.hidden = !hasNewWIFI;
//}
//
//
//- (void)leftButtonPressed:(id)sender
//{
//    NSLog(@"___func:%s__",__func__);
//}
//
//- (void)viewWillDisappear:(BOOL)animated
//{
//    [super viewWillDisappear:animated];
//    [[NSNotificationCenter defaultCenter] removeObserver:self name:TK_FindNewWIFINotification object:nil];
//}



- (void)dealloc
{
    [[NSNotificationCenter defaultCenter] removeObserver:self name:UIApplicationDidBecomeActiveNotification object:nil];
}


- (void)findNewWIFI
{
    __weak __typeof(self)weakSelf = self;
    [self.discoverHelper discoverWIFISuccess:^(BOOL succ, id responseObject, NSString *msg) {
        __strong __typeof(weakSelf)strongSelf = weakSelf;
        NSLog(@"responseObject:%@",responseObject);
        if (responseObject)
        {
            strongSelf.responseDict = responseObject;
            NSString *info = responseObject[@"info"];
            if ([info isEqualToString:@"InterNetNotConnected"])
            {
                [self showNOWIFIDeviceView];
            }
            else if ([info isEqualToString:@"InterNetConnected"])
            {
                NSString *deviceID = responseObject[@"deviceID"];
                [strongSelf checkDeviceInBindWithDeviceID:deviceID];
            }
        }
        else
        {
            [self showNOWIFIDeviceView];
        }
        
    } failure:^(NSError *error) {
        [self showNOWIFIDeviceView];
    }];
}



- (void)checkDeviceInBindWithDeviceID:(NSString *)deviceID
{
    if (deviceID) {
        WEAKSELF
        [self.discoverHelper getWIFIBindDeviceWithDeviceID:deviceID success:^(BOOL succ, id responseObject, NSString *msg) {
            STRONGSELF
            if (responseObject) {
                BOOL bindOrNot = [responseObject[@"isBind"] boolValue];
                if (!bindOrNot)
                {
                    [strongSelf hiddenNoWIFIDeviceView];
                    strongSelf.contentList = [NSMutableArray arrayWithObject:responseObject];
                    [strongSelf.tableView reloadData];
                }
                else
                {
                    WIFIModel *wifi = [UserSingleton shareInstance].userModel.wifi;
                    if (!wifi)
                    {
                        [strongSelf showNOWIFIDeviceView];
                    }
                    else
                    {
                        [strongSelf hiddenNoWIFIDeviceView];
                        strongSelf.contentList = [NSMutableArray arrayWithObject:responseObject];
                        [strongSelf.tableView reloadData];
                    }
                }
            }
        } failure:^(NSError *error) {
            NSString *failedReason = [error localizedDescription];
            [self stopActivityWithActivity:self.activity title:failedReason];
        }];
    }
    
}



- (void)showNOWIFIDeviceView
{
    
    
    self.showNoWIFIView = [[UIView alloc] init];
    self.showNoWIFIView.backgroundColor = [UIColor whiteColor];
    [self.view addSubview:self.showNoWIFIView];
    
    [self.showNoWIFIView makeConstraints:^(MASConstraintMaker *make) {
        make.edges.equalTo(self.view);
    }];
    
    [self showNetworkExceptionWithView:self.showNoWIFIView andTitle:@"您还没有绑定任何一个小叶WIFI设备\n还没有小叶WIFI？赶快去买一个吧!" andButtonTitle:nil andBtnBlock:nil];
    
    UIButton *buyNowBtn = [self.showNoWIFIView addButtonWithTitle:@"立即购买" target:self action:@selector(buyNowButtonPressed:)];
    [buyNowBtn setBackgroundImage:[UIImage imageWithColor:NavgationBarBackgroundColor] forState:UIControlStateNormal];
    [buyNowBtn makeConstraints:^(MASConstraintMaker *make) {
        make.bottom.equalTo(self.view.bottom).offset(-80);
        make.left.equalTo(23);
        make.right.equalTo(-23);
        make.height.equalTo(45.0f);
    }];
}


- (void)hiddenNoWIFIDeviceView
{
    [self.showNoWIFIView removeFromSuperview];
    self.showNoWIFIView = nil;
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}




#pragma mark -
#pragma mark - UITableViewDataSource
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return [self.contentList count];
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString * cellIdentifier = @"BindWiFITableViewCell";
     BindWiFITableViewCell*cell = (BindWiFITableViewCell *)[tableView dequeueReusableCellWithIdentifier:cellIdentifier];
    
    NSDictionary *dict = self.contentList[indexPath.row];
    BOOL isBind = [dict[@"isBind"] boolValue];
    if (!isBind)
    {
        cell.bindButton.hidden = NO;
        NSString *ssid = self.responseDict[@"ssid"];
        if (ssid)
        {
            NSString *string = [NSString stringWithFormat:@"未绑定的小叶WIFI%@",ssid];
            NSMutableAttributedString *mutableString = [[NSMutableAttributedString alloc] initWithString:string];
            NSRange range = [string rangeOfString:ssid];
            [mutableString addAttributes:@{NSForegroundColorAttributeName:NavgationBarBackgroundColor} range:NSMakeRange(0, range.location)];
            [mutableString addAttributes:@{NSForegroundColorAttributeName:SeparatorLineColor} range:range];
            cell.unBindDeviceLabel.attributedText = mutableString;
        }
        else
        {
            cell.unBindDeviceLabel.text = @"未绑定的小叶WIFI";
        }
    }
    else{
        NSDictionary *param = self.contentList[indexPath.row];
        NSArray *array = [param objectForKey:@"bindDevice"];
        cell.unBindDeviceLabel.textColor = NavgationBarBackgroundColor;

        if ([array count] > 0) {
            BindDeviceModel *model = [BindDeviceModel objectWithKeyValues:array[0]];
            NSString *ssid = model.ssid;
            NSString *user = model.userID;
            NSString *text = [NSString stringWithFormat:@"小叶WIFI:%@已经被%@绑定",ssid,user];
            cell.unBindDeviceLabel.text = text;
        }
        cell.bindButton.hidden = YES;
    }

    WEAKSELF
    [cell setBindButtonClick:^{
        STRONGSELF
        [strongSelf gotoBindViewController];
    }];
    return cell;
}


#pragma mark -
#pragma mark - UITableViewDelegate
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 44.0f;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
}


#pragma mark -
#pragma mark   IBActions
- (void)rightButtonPressed:(UIButton *)sender
{
    [self pushViewControllerWithClassName:NSStringFromClass([MyViewController class])];
}



- (void)buyNowButtonPressed:(UIButton *)sender
{
    BuyWIFIViewController *buyWIFI = [[BuyWIFIViewController alloc] init];
    BaseNavigationViewController *nav = [[BaseNavigationViewController alloc] initWithRootViewController:buyWIFI];
    [self presentViewController:nav animated:YES completion:^{
        
    }];
}



- (void)gotoBindViewController
{
    BindDeviceViewController *viewcontroller = [[BindDeviceViewController alloc] init];
    viewcontroller.responseDict = self.responseDict;
    [self.navigationController pushViewController:viewcontroller animated:YES];
}








@end
